package com.shuiyun.jtt.config;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ObjectUtil;
import com.shuiyun.jtt.anno.Mapping;
import com.shuiyun.jtt.anno.Message;
import com.shuiyun.jtt.handler.Handler;
import com.shuiyun.jtt.utils.CacheKey;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.util.Set;

/**
 * @author shuiyun
 * @program gateway
 * @description 缓存配置类
 * @date 2022-04-19 19:46
 **/
public class CacheConfig {

    private static final String MESSAGE_PACKAGE_PATH = "com.shuiyun.jtt.message.jt808";
    private static final String ENDPOINT_PACKAGE_PATH = "com.shuiyun.jtt.endpoint";

    /**
     * 初始化入口
     * @author shuiyun
     * @date 2022-04-19 19:57
     */
    @PostConstruct
    public void init(){
        // 扫描加载所有的message
        initMessage();
        // 扫描加载所有的endpoint
        initEndpoint();
    }

    /**
     * 扫描所有的处理方法
     * @author shuiyun
     * @date 2022-04-20 14:06
     */
    private void initEndpoint() {
        Set<Class<?>> classes = ClassUtil.scanPackage(ENDPOINT_PACKAGE_PATH);
        classes.forEach(clazz -> {
            for (Method method : clazz.getMethods()) {
                Mapping mapping = method.getAnnotation(Mapping.class);
                if (ObjectUtil.isNotNull(mapping)){
                    Handler handler = new Handler(clazz, method, mapping.desc());
                    for (int id : mapping.types()) {
                        CacheKey.instance.getHandlerMap().put(id,handler);
                    }
                }
            }
        });
    }

    /**
     * 扫描加载所有的message
     * @author shuiyun
     * @date 2022-04-20 10:20
     */
    private void initMessage(){
        Set<Class<?>> classes = ClassUtil.scanPackage(MESSAGE_PACKAGE_PATH);
        classes.forEach(clazz -> {
            Message message = clazz.getAnnotation(Message.class);
            if (ObjectUtil.isNull(message)){
                return;
            }
            for (int id : message.value()) {
                CacheKey.instance.getMessageMap().put(id,clazz);
            }
        });
    }
}
